package cn.youyeku.sockettransmission.CLIENT;



import android.util.Log;

import com.google.gson.Gson;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.youyeku.sockettransmission.ui.ConstantAppConfig;
import cn.youyeku.sockettransmission.utils.LogUtils;

/**
 * Created by youye on 17-6-8.
 */
public class FileClient extends BaseClientSocket {
    FileClientListener mFileClientListener;
    public FileClient(String ip_address, int port, String mSocketType) {
        //子类->父类->执行父类
        super(port, ip_address, mSocketType);

    }

    @Override
    protected void onGetRecycle() throws IOException {

        LogUtils.i("-------接收文件等待--------------");

       getFile();


        LogUtils.i("-------接收文件完成--------------");

    }

    public void sendFile(String path) throws IOException, InterruptedException {

        Log.w("---- ---", "发送数据-------------" + path);

        File file = new File(path);


        //打包所需要的数据
        SendPacket sendPacket = new SendPacket(1, file.getName(), file.length());
        byte[] send = new byte[200];

        String data = new Gson().toJson(sendPacket);
        byte[] info = data.getBytes("UTF-8");

        System.arraycopy(info, 0, send, 0, info.length);

        Log.w("---- ---", send.length + " 发送延迟-------------" + data);
        mOutWrite.write(send);
        mOutWrite.writeByte(1);
        mOutWrite.flush();
        if (!file.exists()) {
            System.out.print("文件不存在");
            return;
        }
        FileInputStream fis = new FileInputStream(file);
        byte[] data_read = new byte[1024];
        byte[] end_data= new byte[1024];
        int length = 0;
        //返回int what 用于判断当前进度
        //1 完成 0 未完成
        //分段 1 类型 1024 数据 1 是否是尾部

        while (true){
            length = fis.read(data_read, 0, data_read.length);
            if(length ==-1){
                mOutWrite.writeByte(1);
                mOutWrite.write(end_data);
                //完成写
                mOutWrite.writeInt(0);
                mOutWrite.writeByte(1);
                mOutWrite.flush();
                LogUtils.w("");
                break;
            }
            else {
                //类型
                mOutWrite.writeByte(1);
                //数据域
                mOutWrite.write(data_read);

                mOutWrite.writeInt(length);
                //是否结尾
                mOutWrite.writeByte(0);
                //写出
                mOutWrite.flush();
            }

        }

        fis.close();

        Log.w("-------", "\n发送数据完成 -------------");
    }


    public void setFileClientListener(FileClientListener mFileClientListener) {
        this.mFileClientListener = mFileClientListener;
    }

    public void getFile() throws IOException {
        //获取文件 接收字节流
        Log.w("---", " FileRec wait");

        byte[] info = new byte[201];
        mInRead.readFully(info);
        byte one = info[info.length-1];
        if(String.valueOf(one).equals("1")){
            Log.w("","接收完整");
        }
        int size = 0;
        //获取数据域
        for (int i =0;i<info.length;i++)
        {
            if(info[i]==0){
                size=i;
                break;
            }
        }
        byte[] decode  = new byte[size];
        System.arraycopy(info,0,decode,0,decode.length);
        String msg = new String(decode);
        Log.w("++++++", msg);
        SendPacket sendPacket = new Gson().fromJson(msg, SendPacket.class);
        File f = new File(ConstantAppConfig.SAVE_PATH, sendPacket.getFile_name());
        LogUtils.w(f.getAbsolutePath());

        FileOutputStream fos = new FileOutputStream(f);

        byte[] bytes = new byte[1026+4];
        int bytes_len ;


        int len_data = bytes.length;
        LogUtils.w("传输的每个字节长度"+len_data);
        while (true) {
            mInRead.readFully(bytes, 0, len_data);
            if(String.valueOf(bytes[len_data-1]).equals("1")){
                Log.w(" 读到文件","end");
                break;
            }

            bytes_len = readInt(bytes,1025,4) ;


            //假设开始从0 读取 则 读取20 为0 - len-1 添加开始的修正 1-len
//            fos.write(bytes, 1, bytes_len);
//            LogUtils.w("写入长度"+bytes_len);
            fos.write(bytes, 1, bytes_len);
            fos.flush();
        }

        fos.close();
        Log.w("", "接收完成 关闭流");

        mFileClientListener.onRecSuccess(sendPacket.getFile_name());

    }


    public int readInt(byte[] data,int start,int offset){

        byte[] len_bytes= new byte[4];
        System.arraycopy(data,start,len_bytes,0,offset);

        return   len_bytes[3] & 0xFF |
                (len_bytes[2] & 0xFF) << 8 |
                (len_bytes[1] & 0xFF) << 16 |
                (len_bytes[0] & 0xFF) << 24;

    }

    public interface FileClientListener{
        void  onRecFile();
        void onRecSuccess(String fileName);
    }


}
